<?php
  
class Log {
	private static $first = null;
	private static $entries = array();
	private static $immediate = false;
	
	public static function HasEntries(){ return count(self::$entries) > 0; }
	private static function RenderEntry($index=null){
		if (is_null($index)) $index = count(self::$entries) - 1;
		$prev_time = $index == 0 ? 0 : self::$entries[$index-1][0];
		echo '<pre>';
		echo self::format_timespan(self::$entries[$index][0]) . ' <i>(+' . self::format_timespan(self::$entries[$index][0] - $prev_time) . ')</i>: ' . self::$entries[$index][1] . "\n";
		echo '</pre>';
		echo "\n";
	}
	
	
	public static function IsImmediateFlushingEnabled(){
		return self::$immediate;
	}
	public static function EnableImmediateFlushing(){
		self::$entries = array();
		self::$immediate = true;
		while(ob_get_level()!=0) ob_end_clean();
		ob_start();
	}
	  
	public static function Init(){ 
		self::$entries = array();
		self::$first =  microtime(true); 
	}
  private static function Add($message) {
  	$time = microtime(true);
  	if (is_null(self::$first)) {
  		self::$first = $time;
  		$e = array(0,$message);
		}
		else $e = array($time - self::$first,$message);
			
 		self::$entries[] = $e;
		if (self::$immediate){
			while(ob_get_level()!=0) ob_end_clean();
			self::RenderEntry();
			flush();
			ob_start();
		}
	}
	private static function format_timespan($timespan){
		$sec = intval( $timespan );
		$msec = intval ( ($timespan - $sec) * 1000 );
		$min = intval( $sec / 60 );
		$sec -= $min * 60;
		$r = '';
		if ($min < 10) $r .= '0';
		$r.=$min . '\'';
		if ($sec < 10) $r .= '0';
		$r.=$sec . '"';
		if ($msec < 10) $r .= '0';
		if ($msec < 100) $r .= '0';
		$r.=$msec;
		return $r;
	}
	public static function Render(){
		for ($i = 0; $i<count(self::$entries); $i++)
			self::RenderEntry($i);
	}	
	
	
  public static function WriteException(Exception $ex){ self::Add('<b>'. get_class($ex) . '</b><br/><br/><div style="border-left:1px solid #999999;margin-left:10px;padding:10px;">' . $ex->getMessage() . '<br/><br/><div style="color:#777777;">'. $ex->getTraceAsString().'</div></div>'); }
	
  public static function Write($message){ self::Add($message); }
	public static function Dump($var){
		ob_start(); var_dump($var); $s = ob_get_clean();
		self::Add($s);
	}
	public static function Tick(){ self::Write('&bull;'); }
	public static function TickImmediate(){ self::Tick(); self::RenderEntry(); }

	public static function DumpImmediate($var){
		self::Dump($var);
		self::RenderEntry();
	}
  public static function WriteImmediate($message=null){
		self::Write($message);
		self::RenderEntry();
	}
	

	public static function Save(){
		ob_start();
		self::Render();
		$log = ob_get_clean();
		file_put_contents('./log_'.Oxygen::GetWindowID()->AsHex().date('__Y_m_d__H_i_s').'.log',$log);
	}
}



?>
